package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 黑马程序员
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车
     *
     * @param shoppingCart 购物车当前产品数据
     * @param uid          用户的uid
     * @return ShoppingCart
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart, Long uid) {
        //封装uid
        shoppingCart.setUserId(uid);

        //1.查询当前商品是否被用户买过
        //根据用户的id与菜品id或套餐id查询购物车记录对象
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByUidAndDidOrSetmealId(shoppingCart);

        //2.记录对象有值，说明加入过购物车，份数+1
        if (dbShoppingCart != null) {
            dbShoppingCart.setNumber(dbShoppingCart.getNumber() + 1);
            //更新数据库的数量
            shoppingCartMapper.updateNumberById(dbShoppingCart);
        } else {

            //3.记录对象没有值，说明购物车没有加入过这个菜品或套餐，插入一条新记录，默认份数为1
            //完善shoppingCart数据
            shoppingCart.setUserId(uid); //购物车所属用户
            shoppingCart.setNumber(1); //初始化份数为1
            shoppingCart.setCreateTime(LocalDateTime.now());
            //插入到数据库
            shoppingCartMapper.save(shoppingCart);

            dbShoppingCart = shoppingCart;
        }

        //4.返回购物车记录对象
        return dbShoppingCart;
    }

    /**
     * 获取用户的购物车集合
     *
     * @param uid 用户id
     * @return List
     */
    @Override
    public List<ShoppingCart> findAllByUid(Long uid) {
        return shoppingCartMapper.findAllByUid(uid);
    }

    /**
     * 根据用户id删除购物车数据
     *
     * @param uid
     */
    @Override
    public void clean(Long uid) {
        shoppingCartMapper.clean(uid);
    }

    @Override
    public void sub(ShoppingCart shoppingCart) {
        //根据用户的id与菜品id或套餐id查询购物车记录对象
        ShoppingCart dishIdAndUserId = shoppingCartMapper.findByDishIdAndUserId(shoppingCart);
        if(dishIdAndUserId.getNumber()==1){
            shoppingCartMapper.deleteSub(shoppingCart);
        }
        dishIdAndUserId.setNumber(dishIdAndUserId.getNumber() - 1);
        shoppingCartMapper.updateSub(dishIdAndUserId);
        }
    }

